<?php

namespace app\model;

use app\model\AdminsModel;
use app\model\UsersModel;

class OperationLogModel extends BaseModel
{
    /**
     * 与模型关联的表名
     *
     * @var string
     */
    protected $table = 'operation_logs';

    /**
     * 属性类型转换
     *
     * @var array
     */
    protected $casts = [
        'is_success' => 'boolean',
        'duration' => 'float',
        'response_code' => 'integer',
        'created_at' => 'datetime:Y-m-d H:i:s'
    ];

    /**
     * 关联管理员
     */
    public function admin()
    {
        return $this->belongsTo(AdminsModel::class, 'admin_id');
    }

    /**
     * 关联普通用户
     */
    public function user()
    {
        return $this->belongsTo(UsersModel::class, 'user_id');
    }

    /**
     * 获取操作用户信息（管理员或普通用户）
     */
    public function getOperatorAttribute()
    {
        if ($this->user_type === 'admin' && $this->admin_id) {
            return $this->admin;
        } elseif ($this->user_type === 'user' && $this->user_id) {
            return $this->user;
        }
        return null;
    }

    /**
     * 获取操作用户名称
     */
    public function getOperatorNameAttribute()
    {
        $operator = $this->operator;
        if (!$operator) {
            return '未知用户';
        }

        if ($this->user_type === 'admin') {
            return $operator->username ?? '管理员';
        } else {
            return $operator->nickname ?? $operator->username ?? '用户';
        }
    }
}